package eSignDemo

import (
	"context"
	"github.com/renxingcode/esign-go-sdk"
	"github.com/renxingcode/esign-go-sdk/api"
	eSignTypes "github.com/renxingcode/esign-go-sdk/types"
	"github.com/renxingcode/esign-go-sdk/utils"
	"github.com/zeromicro/go-zero/core/logx"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
)

type CreateByTemplateLogic struct {
	logx.Logger
	ctx      context.Context
	svcCtx   *svc.ServiceContext
	eSignSdk *esign.Client
}

// 通过模板创建合同文件
func NewCreateByTemplateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateByTemplateLogic {
	return &CreateByTemplateLogic{
		Logger:   logx.WithContext(ctx),
		ctx:      ctx,
		svcCtx:   svcCtx,
		eSignSdk: svcCtx.ESignSdk,
	}
}

func (l *CreateByTemplateLogic) CreateByTemplate(req *types.CreateByTemplateRequest) (resp *types.CommonResponse, err error) {
	// 1. 获取模板信息
	templateDetail, err := l.eSignSdk.Template.GetESignTemplateDetail(req.ESignTemplateId, true, req.WriteLog)
	if err != nil {
		return nil, err
	}

	// 2. 判断e签宝返回的code是否成功
	if templateDetail.Code != api.ESignResponseCodeSuccess {
		return nil, api.GetESignResponseError(templateDetail)
	}

	// 3. 解析模板数据到结构体
	eSignTemplateData := eSignTypes.GetESignTemplateDetailResponse{}
	err = utils.JsonUnmarshalToStruct(templateDetail.Data, &eSignTemplateData)
	if err != nil {
		return nil, err
	}

	// 4. 生成合同模板数据
	eSignTemplateDocFileId := eSignTemplateData.Docs[0].FileId
	eSignTemplateDocFileName := "rxESignGoSdkDemo-" + utils.GetCurrentTime() + "-" + eSignTemplateData.Docs[0].FileName //自定义生成后的模板文件名称 todo 改为你自己的格式
	eSignTemplateDocSimpleFormFields := make(map[string]string)
	for _, field := range eSignTemplateData.Participants {
		for _, component := range field.Components {
			//这里先简单粗暴的把控件的名称赋值给控件编码,正常业务场景下应该根据你自己的业务去赋值 todo
			eSignTemplateDocSimpleFormFields[component.ComponentKey] = component.ComponentName
		}
	}

	// 5. 请求e签宝创建合同模板数据CreateESignFileByTemplateRequest
	createByTemplateResponse, err := l.eSignSdk.Template.CreateByTemplate(eSignTemplateDocFileId, eSignTemplateDocFileName, eSignTemplateDocSimpleFormFields, true)
	if err != nil {
		return nil, err
	}
	if createByTemplateResponse.Code != api.ESignResponseCodeSuccess {
		return nil, api.GetESignResponseError(createByTemplateResponse)
	}
	createByTemplateResponseData := eSignTypes.CreateESignFileByTemplateResponse{}
	err = utils.JsonUnmarshalToStruct(createByTemplateResponse.Data, &createByTemplateResponseData)
	if err != nil {
		return nil, err
	}

	// 6.将e签宝返回的downloadUrl上传到自己服务器或OSS todo
	createByTemplateResponseData.DownloadOssUrl = "todo_your_server_file_url"
	createByTemplateResponseData.TemplateId = req.ESignTemplateId

	return types.SuccessResponse(createByTemplateResponseData, l.ctx), nil
}
